import { instantiate } from 'cc';
import { _decorator, Component, Node, Prefab } from 'cc';
import { BaseView } from '../../../../scripts/libs/rxjs/cc3/BaseView';
import { Card } from './Card';
const { ccclass, property } = _decorator;

@ccclass('CardGroup')
export class CardGroup extends BaseView {

    @property(Prefab)
    cardPrefab: Prefab = null;

    @property(Node)
    cardEmptyNode: Node = null;

    cards: Card[] = [];

    clearCards() {
        this.cards = [];
        this.cards.map(_ => _).forEach(_ => _.node.destroy());
        this.refreshCardEmpty();
    }

    addCard(cardId: number) {
        this.log('addCard', cardId);
        let cardNode = instantiate(this.cardPrefab);
        let card = cardNode.getComponent(Card);
        card.cardId.value = cardId;
        cardNode.parent = this.node;
        this.cards.push(card);
        this.refreshCardEmpty();
    }

    removeCard(cardId: number, useOriCardId: boolean = false) {
        this.log('remoteCard', cardId);
        let index = this.cards.findIndex(_ => _.cardId.value == cardId);
        if (useOriCardId) index = this.cards.findIndex(_ => _.cardIdOri == cardId);
        if (index >= 0) {
            this.cards[index].willDestroy = true;
            this.cards[index].node.destroy();
            this.cards.splice(index, 1);
        }
        this.refreshCardEmpty();
    }

    refreshCardEmpty() {
        this.cardEmptyNode.active = this.cards.length == 0;
    }

    getCardsId(): number[] {
        let result = [];
        for (let i = 0; i < this.cards.length; i++) {
            if (this.cards?.[i]?.cardId.value >= 0) {
                result.push(this.cards[i].cardId.value);
            }
        }
        return result;
    }
}

